package com.ars.personalInfomation;

import com.ars.db.DBTools;
import com.ars.main.User;

import javax.swing.*;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UpdateName {

    //获取用户id
    private int getUserId() {
        int userId = -1;
        String sql = "SELECT wid FROM website WHERE name = '" + getUserName() + "';";
        ResultSet rs = new DBTools().query(sql);
        try {
            if (rs.next()) {
                return rs.getInt("wid");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return userId;
    }

    //获取用户名
    private String getUserName() {
        return User.getName();
    }

    //显示弹出框
    public void show() {
        String inputValue = JOptionPane.showInputDialog("请输入新的用户名：", getUserName());
        updateDB(inputValue);
    }

    //更新数据库
    private void updateDB(String newName) {
        if (newName == null) {
            return;
        } else if (newName.equals("")) {
            JOptionPane.showMessageDialog(null, "用户名不能为空！", "警告", JOptionPane.ERROR_MESSAGE);
        } else {
            String sql = "UPDATE website set name = '" + newName + "' WHERE wid = " + getUserId();
            new DBTools().update(sql);
            JOptionPane.showMessageDialog(null, "操作成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
        }

    }

}
